08. Using Return Values

Using Return Values

Returning a value from a function is great, but what's the use of a return value if you're not going to use the value to do something?

A function's return value can be stored in a variable or reused throughout your program as a function argument. Here, we have a function that adds two numbers together, and another function that divides a number by 2. We can find the average of 5 and 7 by using the add() function to add a pair of numbers together, and then by passing the sum of the two numbers add(5, 7) into the function divideByTwo() as an argument.

And finally, we can even store the final answer in a variable called average and use the variable to perform even more calculations in more places!

// returns the sum of two numbers
function add(x, y) {
  return x + y;
}


// returns the value of a number divided by 2
function divideByTwo(num) {
  return num / 2;
}


var sum = add(5, 7); // call the "add" function and store the returned value in the "sum" variable
var average = divideByTwo(sum); // call the "divideByTwo" function and store the returned value in the "average" variable

What Will This Function Return?

Try predicting what will be printed in the console.log statement below. Then, check your prediction by pasting the code into the JavaScript console. Functions can be tricky, so try figuring it out before running the code!

function addTen(x) {
  return x + 10;
}

function divideByThree(y) {
  return y / 3;
}

var result = addTen(2);
console.log(divideByThree(result));
SOLUTION: 4